package com.jacksen.demo.view.canvas;

import android.animation.ValueAnimator;
import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.LinearGradient;
import android.graphics.Matrix;
import android.graphics.Paint;
import android.graphics.Shader;
import android.support.annotation.ColorRes;
import android.util.AttributeSet;
import android.widget.TextView;

/**
 * @author jacksen
 *         <br/>
 * @since 2017/7/1
 */

public class FlickerTextView extends android.support.v7.widget.AppCompatTextView {

    private Paint paint;

    private LinearGradient linearGradient;

    private int offset = 0;

    private Matrix matrix = new Matrix();

    public FlickerTextView(Context context) {
        this(context, null);
    }

    public FlickerTextView(Context context, AttributeSet attrs) {
        this(context, attrs, 0);
    }

    public FlickerTextView(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);

        init();
    }

    private void init() {
        paint = getPaint();

    }

    @Override
    protected void onLayout(boolean changed, int left, int top, int right, int bottom) {
        super.onLayout(changed, left, top, right, bottom);

        ValueAnimator animator = ValueAnimator.ofInt(0, 2 * getMeasuredWidth());
        animator.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
            @Override
            public void onAnimationUpdate(ValueAnimator animation) {
                offset = (int) animation.getAnimatedValue();
                postInvalidate();
            }
        });

        animator.setRepeatMode(ValueAnimator.RESTART);
        animator.setRepeatCount(ValueAnimator.INFINITE);
        animator.setDuration(1200);
        animator.start();

        // new
        linearGradient = new LinearGradient(-getMeasuredWidth(), 0, 0, 0, new int[]{getCurrentTextColor(), Color.RED, Color.BLUE, getCurrentTextColor()}, null, Shader.TileMode.CLAMP);
        paint.setShader(linearGradient);
    }

    @Override
    protected void onDraw(Canvas canvas) {

        matrix.setTranslate(offset, 0);
        linearGradient.setLocalMatrix(matrix);

        paint.setShader(linearGradient);

        super.onDraw(canvas);

    }


}
